#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

#define N 2
#define NUMBER 1024

void Writer(pid_t wid)
{
    string s = "hello liunx!";
    pid_t self = getpid();
    int number = 0;

    char buffer[NUMBER];
    while (true)
    {
        sleep(1);
        
        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number);
        write(wid, buffer, strlen(buffer));
        number++;

        if (number == 6)  break;
    }
}

void Reader(pid_t rid)
{
    char buffer[NUMBER] = {0};

    while (true)
    {
        buffer[0] = 0;
        ssize_t re = read(rid, buffer, sizeof(buffer));

        if (re > 0)
        {
            buffer[re] = 0;
            cout << "father get message" << "[" << getpid() << "]" << "# " << buffer << endl;
        }
        else if (re == 0)
        {
            cout << "father file check done" << endl;
            break;
        }
        else
        {
            break;
        }
    }
}

int main()
{
    int pipepid[N] = {0};
    int n = pipe(pipepid);
    if (n < 0)
    {
        return 1;
    }

    pid_t id = fork();
    if (id == 0)
    {
        close(pipepid[0]);

        Writer(pipepid[1]);

        close(pipepid[1]);
        exit(0);
    }
    else if (id < 0)
    {
        return 2;
    }

    close(pipepid[1]);
    Reader(pipepid[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if (rid < 0)
    {
        return 3;
    }
    close(pipepid[0]);


    return 0;
}
